<?php

namespace Tian\Controller;

use PclZip;

class SourceController extends CommonController {

    public function lists() {
        $s_admin_uid = getAdminId();
        $sql = "1=1";

        if ($s_admin_uid != 1) {
            $sql .= " AND uid = " . $s_admin_uid . "";
        }
        $keyword = trim(I('get.keyword'));


        $is_check = I("get.is_check");
        if ($is_check >= 0 && $is_check != '') {
            $sql .= " AND is_check = " . $is_check . "";
        }
        $is_show = I("get.is_show");
        if ($is_show >= 0 && $is_show != '') {
            $sql .= " AND is_show = " . $is_show . "";
        }
        $points = trim(I('get.points', 0, 'int'));
        $points2 = trim(I('get.points2', 0, 'int'));
        if ($points > 0 && $points2 > 0) {

            $sql .= " AND points between '" . $points . "' AND '" . $points2 . "' ";
        } else {
            if ($points > 0) {
                $sql .= " AND points >= '" . $points . "'";
            }
            if ($points2 > 0) {
                $sql .= " AND points <= '" . $points2 . "'";
            }
        }

        $sql_order = "id DESC";
//        $is_complete = I("get.is_complete");
//        if ($is_complete == -1) {
//
//            $sql .= " AND time_create =0 AND is_check =0 AND id>5395";
//        } elseif ($is_complete == 2) {
//            $sql .= " AND time_create >0 AND is_check =1 AND id>5395";
//        } elseif ($is_complete == 1 && $is_complete != '') {
//            $sql_order = "time_create desc,id DESC";
//            $sql .= " AND time_create >0 AND is_check =0 AND id>5395";
//        }
//        if($keyword == ''){
//              $sql .= " AND is_download = 0";
//        }
        $is_download = I("get.is_download");


        if (is_numeric($keyword) == 1) {
            $sql = "id = '" . $keyword . "'";
        } else {

            if (!empty($keyword)) {
                $sql .= " AND (name like '%" . $keyword . "%' or keywords like '%" . $keyword . "%' or source like '%" . $keyword . "%')";
            } else {
                if ($is_download != '') {
                    $sql .= " AND is_download = " . $is_download . "";
                } else {
                    $sql .= " AND is_download = 0";
                }
            }
        }

        $count = M('source')->where($sql)->count();    //计算总数
        $Page = new \Think\Page($count, 20);
        $lists = M('source')->where($sql)->limit($Page->firstRow . ',' . $Page->listRows)->order($sql_order)->select();
//echo $sql;
        $new_id = M('source')->max("id") - 30;
//        print_r($lists);exit;
        foreach ($lists as $k => $v) {
            if ($v['id'] < $new_id) {
                //  $lists[$k]['downloads'] = M("download")->field("uid,addtime,points")->where("tid = " . $v['id'] . " AND mtype = 15")->order($sql_order)->select();
            }
            $not_complete = '';
            if ($v['time_create'] == 0) {
                $logo = "sources/" . getFileBei($v['id']) . $v['id'] . "/" . "middle.jpg";
                if (!file_exists($logo)) {
                    $not_complete .="图片、";
                }
                if ($v['cat_id'] == '') {
                    $not_complete .="类别、";
                }
                if ($v['tags'] == '') {
                    $not_complete .="标签、";
                }
                if ($v['points'] >= 30) {
                    
                } else {
                    $not_complete .="下载火币、";
                }
                if ($v['color_id'] == '') {
                    $not_complete .="类别、";
                }
                if ($v['lay_id'] == '') {
                    $not_complete .="布局、";
                }
                if ($v['development_id'] > 0) {
                    
                } else {
                    $not_complete .="开发程序、";
                }

                if (strlen($v['content']) > 10) {
                    
                } else {
                    $not_complete .="教程至少10个字符、";
                }


                if ($v['content_first'] == '') {
                    $not_complete .="详情页开头、";
                }
                if ($v['keywords'] == '') {
                    $not_complete .="关键字、";
                }
                if ($v['description'] == '') {
                    $not_complete .="描述、";
                }
                if ($not_complete != '') {
                    $not_complete = substr($not_complete, 0, -3);
                }
            } else {
                
            }
            $lists[$k]['not_complete'] = $not_complete;
        }
        $count_not = M("source")->field("id")->where("id>=5395 AND uid =1 AND is_check =0 AND points<=30")->count(); //未分配
        $this->assign("page", $Page->show());
        $this->assign("lists", $lists);
        $this->assign("keyword", $keyword);
        $this->assign("count_not", $count_not);
        $this->assign("is_complete", $is_complete);
        $this->assign("is_download", $is_download);
        $this->assign("is_check", $is_check);
        $this->assign("is_show", $is_show);
        $this->display();
    }

    public function detail() {

        $templatesModel = new \Tian\Model\ModalsModel();
        $id = I('get.id', '0', 'int');

        if ($id > 0) {
            $detail = M('source')->where("id =" . $id . "")->find();
            if (empty($detail)) {
                $this->error("不存在");
            }
            $jsons = json_decode($detail['content'], true);
            $parameters = json_decode($detail['parameters'], true);
            $detail['logo_url'] = getModalsLogo($id, 'middle', 'source');

            if ($id < 15200) {

                $this->clear_downloads($id);
            }
        } else {
            $detail['is_show'] = 1;
            $detail['points'] = 30;
            $detail['money_install'] = -1;
        }
        if (empty($jsons)) {
            $jsons = array(
                0 => array(
                    "content" => "",
                    "html" => ""
                )
            );
        }
        if (empty($parameters)) {
            $parameters = array(
                0 => array(
                    "paras" => ""
                )
            );
        }
        if (!empty($detail['tags'])) {
            $tagsArr = explode(",", $detail['tags']);
            foreach ($tagsArr as $v) {
                $info = M("source_tags")->where("id = " . $v . "")->find();
                $tags[] = $info['name'];
            }
        } else {
            $tags = array(
                0 => "",
                1 => "",
                2 => "",
                3 => "",
                4 => ""
            );
        }
        $modals_cat = $templatesModel->getSourceDictionary('modal_cat_id'); //源码分类
        foreach ($modals_cat as $k => $v) {
            $modals_cat[$k]['sub'] = M("source_dictionary")->where("pid = " . $v['id'] . " AND is_check = 1")->order("ord ASC")->select();
        }
        $modals_color = $templatesModel->getSourceDictionary('modal_color_id'); //源码颜色
        $modals_lay = $templatesModel->getSourceDictionary('modal_lay_id'); //源码布局
        $modals_development = $templatesModel->getSourceDictionary('modal_development_id'); //源码布局

        $next = M('source')->field("name,id")->where("id > " . $id . "")->order("id ASC")->find();
        $prev = M('source')->field("name,id")->where("id < " . $id . "")->order("id DESC")->find();
        $downloads = M("download")->field("uid,addtime,edittime,points")->where("tid = " . $id . " AND mtype = 15")->order("id DESC")->select();
//        print_r($downloads);
        $this->assign("next", $next);
        $this->assign("prev", $prev);
        $this->assign("modals_cat", $modals_cat);
        $this->assign("modals_color", $modals_color);
        $this->assign("modals_lay", $modals_lay);
        $this->assign("modals_development", $modals_development);
        $this->assign("detail", $detail);
        $this->assign("mtype", 'modals');
        $this->assign("utype", 'source');

        $this->assign("id", $id);
        $this->assign("jsons", $jsons);
        $this->assign("parameters", $parameters);
        $this->assign("tags", $tags);
        $this->assign("downloads", $downloads);
        $this->display();
    }

    public function detail_post() {

        $id = I('post.id', '', 'int');
        if ($id == 0) {
            $data['uid'] = session("admin_uid");
            $data['is_check'] = 1;
            $data['addtime'] = time();
            $id = M('source')->add($data);
        }
        $file_path = "sources/" . getFileBei($id) . $id . "/";
//        $file_path_demo = $file_path . "demo/";
        checkDirExists($file_path);
        $data['is_original'] = I("post.is_original") == 1 ? 1 : 0;
        $data['is_recommend'] = I("post.is_recommend");
        $data['name'] = trim(I("post.name"));
        $data['cat_id'] = $_POST['cat_id'] ? implode(",", $_POST['cat_id']) : "";

        $data['color_id'] = I("post.modal_color_id") ? implode(",", I("post.modal_color_id")) : "";
        $data['lay_id'] = I("post.modal_lay_id") ? implode(",", I("post.modal_lay_id")) : "";
        $data['development_id'] = I("post.modal_development_id", 0, 'int');
        $data['ord'] = I("post.ord", 0, 'int');
        $data['points'] = I("post.points", 0, 'int');
        $data['points_type'] = 1;
        $data['content_first'] = I("post.content_first");
        $data['details'] = $_POST['details'];
        $data['zip_size'] = I("post.zip_size", 0, 'int');
        $data['is_kaiyuan'] = I("post.is_kaiyuan", 0, 'int');
        $data['is_shouquan'] = I("post.is_shouquan", 0, 'int');
        $data['language'] = I("post.language", 0, 'int');
        $data['money_install'] = I("post.money_install", 0, 'int');

        /*         * **内容**** */
        $json = array();
        $contents = $_POST['contents'];
        $types = $_POST['types'];
        $pics = uploads_pics(I("post.pics"));
        foreach ($contents as $k => $v) {
            if ($v) {
                $json[$k]['content'] = trim($v);
                $json[$k]['type'] = $types[$k];
                $json[$k]['pics'] = $pics[$k];
            }
        }
        $data['content'] = json_encode($json);
        /*         * **参数**** */
        $paras = $_POST['paras'];
        $descriptions = $_POST['descriptions'];
        $defaults = $_POST['defaults'];
        $urls = $_POST['urls'];
        foreach ($paras as $k => $v) {
            if ($v) {
                $parameters[$k]['paras'] = trim(htmlspecialchars($v));
                $parameters[$k]['descriptions'] = trim($descriptions[$k]);
                $parameters[$k]['defaults'] = trim(htmlspecialchars($defaults[$k]));
                $parameters[$k]['urls'] = trim(htmlspecialchars($urls[$k]));
            }
        }
        $data['parameters'] = json_encode($parameters);
        $keywords = str_replace("，", ',', I("post.keywords"));
        $data['keywords'] = implode(',', array_unique(array_filter(explode(",", $keywords))));
        $data['description'] = trim($_POST['description']);
        $data['logo_big'] = I("post.logo_big");
        $data['source'] = $_POST['source'];
        $data['demo_url'] = I("post.demo_url");
        $data['url_wap'] = I("post.url_wap");
        $data['url_weixin'] = I("post.url_weixin");
        $data['url_words'] = I("post.url_words");
        $data['remark'] = I("post.remark");
        $cat_id = $_POST['cat_id'];
        if (count($cat_id) == 1 && $cat_id[0] == 15) {
            $data['type'] = 1;
        } else {
            $data['type'] = 0;
        }
        $data['tags'] = transferTagsIds($_POST['tag'], 15, 1);
        $data['is_show'] = 1;
        $data['is_check'] = I("post.is_check", 0, 'int');
        $data['is_recommend'] = I("post.is_recommend", 0, 'int');


        $data['logo_big'] = $file_path . "big.jpg";
//        echo I("post.logo_big")."***".$data['logo_big'];
        if (I("post.logo_big") && I("post.logo_big") != $data['logo_big']) {
            rename(I("post.logo_big"), $data['logo_big']);

            $height = getMiddleLogo($data['logo_big']);
            if ($height > 0) {
                $src = $data['logo_big'];
                $pic_info = getimagesize($src);
                $pic_width = $pic_info[0];

                if ($pic_width > 300) {
                    $font_size = 14;
                    if ($pic_width >= 500) {
                        $font_size = 18;
                    }


                    $image = new \Think\Image();
                    $image->open($src)->text('https://www.sucaihuo.com/source/' . $id . '', "./fonts/Octanis-SlabRoundedItalic.ttf", $font_size, '#FF0000', \Think\Image::IMAGE_WATER_CENTER)->save($data['logo_big']);
                }

                M('source')->where("id = " . $id . "")->save(array("height" => $height));
            }
        }

        $url_logo_real = $file_path . "url.jpg";
//        echo I("post.logo_big")."***".$data['logo_big'];
//           $data['url_logo'] = 0;
        if (I("post.url_logo") && I("post.url_logo") != $url_logo_real) {
            rename(I("post.url_logo"), $url_logo_real);

            $data['url_logo'] = 1;
        } else {
            
        }
        $data['wangpan_url'] = I("post.wangpan_url");
        if (I("post.wangpan_pwd")) {
            $data['wangpan_pwd'] = getWangpanPwd(I("post.wangpan_pwd"));
//            echo $data['wangpan_pwd'];exit;
        }

        if ($id > 0) {
            $addtime_words_not = array("小额", "挖矿", "贷款", "贷超", "借贷", '理财', '有钱还', '分期', '矿机', '虚拟币', '红包', '微盘', '微交易', '外汇', '区块', '.', '人人', '还款', '打赏', '付钱', '棋牌');
            $is_addtime = 1;
            foreach ($addtime_words_not as $v) {
                if (strstr($data['name'], $v)) {
                    $is_addtime = 0;
                    break;
                }
            }
//            if ($data['points'] < 80 or $data['source'] == 'w') {
//                $is_addtime = 0;
//            }
            if ($is_addtime == 1) {
                $data['addtime'] = time();
            }


            //&& file_exists($data['logo_big'])
//            echo file_exists($data['logo_big']);
            if ($data['cat_id'] != '' && $data['tags'] != '' && $data['points'] >= 30 && $data['color_id'] != '' && $data['lay_id'] != '' && $data['development_id'] != '' && $data['description'] != '' && $data['keywords'] != '' && $data['content_first'] != '' && (strlen($data['content']) > 10) && file_exists($data['logo_big'])) {
                $info = M('source')->field('time_create')->where("id = " . $id . "")->find();
                if ($info['time_create'] == 0) {
                    $data['time_create'] = time();
                }
            }
            M('source')->where("id = " . $id . "")->save($data);
        } else {
            
        }

        if ($id > 0) {
            $this->success('修改成功！', U("Source/detail", array("id" => $id)));
        } else {
            $this->success('添加成功！', U('Source/lists'));
        }
    }

    public function cat() {//源码类别
        $pid = I('get.pid', '0', 'int');
        $sql = "pid = " . $pid . "";
        $keywords = trim(I('get.keywords'));
        if ($keywords) {
            $sql .= " AND name like '%" . $keywords . "%'";
        }
        $count = M('source_dictionary')->where($sql)->count();    //计算总数
        $Page = new \Think\Page($count, C("pagenum"));
        $lists = M('source_dictionary')->where($sql)->limit($Page->firstRow . ',' . $Page->listRows)->order('ord ASC')->select();
        foreach ($lists as $k => $v) {
            $lists[$k]['num'] = M('source_dictionary')->where("pid = " . $v['id'] . "")->count(); //下级个数
            if ($v['tags']) {
                $lists[$k]['tags_num'] = count(explode(",", $v['tags']));
            } else {
                $lists[$k]['tags_num'] = 0;
            }
        }
        $this->assign("page", $Page->show());
        $this->assign("lists", $lists);
        $this->assign("keywords", $keywords);
        $this->assign("pid", $pid);
        $this->display();
    }

    public function cat_detail() {//源码类别详情
        $id = I("get.id", 0, 'int');
        if ($id > 0) {
            $detail = M('source_dictionary')->where("id = " . $id . "")->find();
        } else {
            $detail['pid'] = I("get.pid", 0, 'int');
            $detail['is_check'] = 1;
        }
        $cats_top = M('source_dictionary')->where("pid = 0")->order('ord ASC')->select();
        foreach ($cats_top as $k => $v) {
            $cats_top[$k]['second'] = M('source_dictionary')->where("pid = " . $v['id'] . "")->order('ord ASC')->select();
        }
        $this->assign("detail", $detail);
        $this->assign("cats_top", $cats_top);
        $this->display();
    }

    public function cat_detail_post() {

        $id = I("post.id", 0, 'int');
        $data['pid'] = I("post.pid", 0, 'int');
        $data['is_check'] = I("post.is_check", 0, 'int');

        $pinfo = M('source_dictionary')->field("pid")->where("id = " . $data['pid'] . "")->find();
        if ($pinfo['pid'] > 0) {
            $level = 2;
        } else if ($pinfo['pid'] == 0) {
            $level = 1;
        } else {
            $level = 0;
        }
        $data['level'] = $level;
        $data['seo_title'] = trim(I("post.seo_title"));
        $data['keywords'] = trim(I("post.keywords"));
        $data['description'] = trim(I("post.description"));
        if ($id > 0) {
            $data['name'] = trim(I("post.name"));
            $data['ord'] = I("post.ord", 0, 'int');
            M('source_dictionary')->where("id = " . $id . "")->save($data);
            $this->success("修改源码类别成功！", session('QUERY_STRING'));
        } else {
            $names = array_unique(array_filter(I('post.name')));
            foreach ($names as $k => $v) {
                if ($v) {
                    $data['name'] = $v;
                    $data['ord'] = I('post.ord', '30', 'int') + $k;
                    M('source_dictionary')->add($data);
                }
            }
            $this->success("添加源码类别成功！", U("Source/cat", array("pid" => $data['pid'])));
        }
    }

    public function tags() {
        $sql = "1=1";
        $keyword = trim(I('get.keyword'));
        if (!empty($keyword)) {
            $sql .= " AND name like '%" . $keyword . "%'";
        }
        $count = M('source_tags')->where($sql)->count();    //计算总数
        $Page = new \Think\Page($count, 100);
        $lists = M('source_tags')->where($sql)->limit($Page->firstRow . ',' . $Page->listRows)->order('ord ASC,id DESC')->select();
        foreach ($lists as $k => $v) {
            $num = M('source')->where("FIND_IN_SET('" . $v['id'] . "',tags)")->count();
            $lists[$k]['num'] = $num;
            M('source_tags')->where("id = '" . $v['id'] . "'")->save(array("num" => $num));
        }
        $this->assign("page", $Page->show());
        $this->assign("lists", $lists);
        $this->assign("keyword", $keyword);
        $this->display();
    }

    public function tags_detail() {//标签详情
        $id = I("get.id", 0, 'int');
        if ($id > 0) {
            $detail = M('source_tags')->where("id = " . $id . "")->find();
        } else {
            $detail['pid'] = I("get.pid", 0, 'int');
            $detail['is_check'] = 1;
        }
        $this->assign("detail", $detail);
        $this->display();
    }

    public function tags_detail_post() {
        $id = I("post.id", 0, 'int');
        $data['is_check'] = I("post.is_check", 0, 'int');
        if ($id > 0) {
            $data['name'] = trim(I("post.name"));
            $data['ord'] = I("post.ord", 0, 'int');
            $data['keywords'] = strtolower(trim(I("post.keywords")));
            $data['description'] = strtolower(trim(I("post.description")));
            M('source_tags')->where("id = " . $id . "")->save($data);
            $this->success("修改源码标签成功！", session('QUERY_STRING'));
        } else {
            $names = array_unique(array_filter(I('post.name')));
            foreach ($names as $k => $v) {
                if ($v) {
                    $data['name'] = $v;
                    $data['ord'] = I('post.ord', '30', 'int') + $k;
                    M('source_tags')->add($data);
                }
            }
            $this->success("添加源码标签成功！", U("Source/tags"));
        }
    }

    //http://admin7788.sucaihuo.com/Tian/Source/update_points_type
    public function update_points_type() {
        $lists = M("source")->field("id,name,points,is_check")->where("points_type = 0 AND is_check =1")->order("id DESC")->limit(100)->select();
        foreach ($lists as $v) {
            $huobi = intval($v['points'] / 10);
            $data['points'] = $huobi;
            $data['points_type'] = 1;
            print_r($data);
            M("source")->where("id = " . $v['id'] . "")->save($data);
        }
        print_r($lists);
    }

    //http://admin7788.sucaihuo.com/Tian/Source/addsource/
    public function addsource() {
        $data['uid'] = 1;
        $data['is_check'] = 0;
        for ($i = 0; $i <= 100; $i++) {
            echo $i;
            $data['name'] = $i;
            $data['addtime'] = time();
            $lastid = M("source")->add($data);
            echo M("source")->getLastSql();
            M("source")->where("id = " . $lastid . "")->save(array("name" => $lastid));
        }
    }

//http://admin7788.sucaihuo.com/Tian/Ajax/update_uid2
    public function links() {//源码添加外链
        $this->display();
    }

    public function links_post() {//源码添加外链
        $sources = array_unique(array_filter(explode("\n", I("post.links"))));
        foreach ($sources as $v) {
            $info = M("source")->where("source = '" . $v . "'")->find();
            if (!$info && $v != '') {
                $data['source'] = $v;
                $data['uid'] = 1;
                $data['addtime'] = time();
                $lastid = M("source")->add($data);
                M("source")->where("id = " . $lastid . "")->save(array("name" => $lastid));
                echo $lastid . "<hr>";
            }
        }
        $this->success("批量添加成功！", U("Source/links"));
    }

    public function clear_ids($id) {

        if ($id > 0) {

//            echo "下载" . M("download")->where("tid = " . $id . " and mtype = 15")->count();
//            echo "<hr>";
//            echo "积分" . M("points")->where("tid = " . $id . " and mtype = 'source'")->count();
//            echo "<hr>";
//            echo "评论" . M("comment")->where("tid = " . $id . " and mtype = 15")->count();
//            echo "<hr>";
//            echo "收藏" . M("collects")->where("tid = " . $id . " and mtype = 15")->count();
//            echo "<hr>";

            M("download")->where("tid = " . $id . " and mtype = 15")->delete();
            M("points")->where("tid = " . $id . " and mtype = 'source'")->delete();
            M("comment")->where("tid = " . $id . " and mtype = 15")->delete();
            M("collects")->where("tid = " . $id . " and mtype = 15")->delete();
            file_put_contents("a.txt", $id);
        }
    }

//http://admin7788.sucaihuo.com/Tian/Ajax/clear_downloads
    //http://www.sucai_houtai.com/Tian/Ajax/clear_downloads
    public function clear_downloads($id) {
//        $id = I("post.id");
        if ($id > 0) {
            $info = M("source")->field("id,name")->where("is_download = '-1' AND id=" . $id . "")->limit(1)->find();

            $this->clear_ids($info['id']);
//            echo $info['id'] . $info['name'];
//            echo "<hr>";
        }
//       $lists =  M("source")->field("id,name")->where("is_download = '-1'")->limit(1)->select();
//       
//       foreach($lists as $v){
//           echo $v['name']."<hr>";
//           $this->clear_ids($v['id']);
//       }
    }

}

?>
    